package com.bjsasc.open.scheduledtask;

import java.io.InputStreamReader;
import java.io.LineNumberReader;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.Set;

import org.apache.commons.lang.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.autoconfigure.condition.ConditionalOnProperty;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;

import com.bjsasc.open.util.StringUtil;


/** 
 * @ClassName: KillInvalidProcessTask 
 * @Description:   后台会跑一个定时任务，每间隔6分钟，从Set集合中扫描所有的进程号，判断在Redis中的String类型的进程号key是否存在 
 * @author zhangbingbing 
 * @date 2024年3月26日 下午4:58:54 
 * @version 1.0 
 */
@Component
@ConditionalOnProperty(prefix = "scheduling", name = "enabled", havingValue = "true")
public class KillInvalidProcessTask {
	
	private static final Logger log = LoggerFactory.getLogger(KillInvalidProcessTask.class);
	
	@Autowired
	private StringRedisTemplate stringRedisTemplate;	 
	 
	private StringUtil stringUtil;	
	
	private static final SimpleDateFormat dataFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
	
    /**
    * @author zhangbingbing   
    * 
    *       定时清空无效的转流进程
    */
	@Scheduled(cron = "0 0/6 * * * ?") // 每间隔6分钟触发一次
	public void killInvalidProcess() {
		log.info("killInvalidProcess开始的时间是 ：{}." ,dataFormat.format(new Date()));
		try{
			Set<String> resultSet =stringRedisTemplate.opsForSet().members(stringUtil.RTSP_TO_RTMP);
			if(resultSet.size()>0) {
				for(String pid:resultSet) {
					log.info("进程号为: " + pid);
		    		String value = stringRedisTemplate.opsForValue().get(stringUtil.FLV_HTTP + pid);
		    		log.info("从redis中查询的结果为:" + value);
		    		if(StringUtils.isEmpty(value)) {
		    			log.info("该进程在redis中不存在,说明无心跳了，可以从set中清除");
		    			
		    			//将该进程号从Set集合中删除
		   			 	stringRedisTemplate.opsForSet().remove(stringUtil.RTSP_TO_RTMP, pid);
		   			 
		   			 	//将该进程从后台关闭
		   			 	String strCommand="kill -9 "+pid;
		   			 	Process process = Runtime.getRuntime().exec(strCommand);
		   			 	log.info(pid + "后台转流进程关闭");
		   			 	
		    		} 
				
				}
				
			}else {
				log.info("rtsp转rtmp对应的set集合里的值为空");
			}
			
		} catch (Exception ex) {
			log.error("定时清空无效的转流进程定时任务执行失败,原因是:" + ex.toString());
		}
		
	}	
	
}
